package com.wing.web.utils;

import java.lang.reflect.Field;
import java.time.LocalDateTime;

public class AddUpdateUtil {
    
    /**
     * 填充用户信息
     * @param obj 需要填充的对象
     */
    public static void fillInsertInfo(Object obj) {
        if (obj == null) return;
        try {
            Class<?> clazz = obj.getClass();
            // 填充创建人ID
            setFieldIfExists(clazz, obj, "creator", JwtUtils.getLoginUserId());
            // 填充创建人名称
            setFieldIfExists(clazz, obj, "creatorName", JwtUtils.getLoginUsername());
            // 填充创建时间
            setFieldIfExists(clazz, obj, "createTime", LocalDateTime.now());
            // 填充更新人ID
            setFieldIfExists(clazz, obj, "modifier", JwtUtils.getLoginUserId());
            // 填充更新人名称
            setFieldIfExists(clazz, obj, "modifierName", JwtUtils.getLoginUsername());
            // 填充更新时间
            setFieldIfExists(clazz, obj, "updateTime", LocalDateTime.now());
        } catch (Exception e) {
            // 这里可以根据需要处理异常
            e.printStackTrace();
        }
    }

    private static void setFieldIfExists(Class<?> clazz, Object obj, String fieldName, Object value) {
        try {
            Field field = clazz.getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(obj, value);
        } catch (NoSuchFieldException ignored) {
            // 字段不存在则忽略
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
